<?php

namespace app\modules\admin\models;

use app\modules\admin\components\Category;
use app\modules\admin\components\Configs;
use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%menu}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $parent
 * @property string $route
 * @property integer $order
 * @property resource $data
 *
 * @property Menu $parent0
 * @property Menu[] $menus
 */
class Menu extends ActiveRecord
{
    public $parent_name;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return Configs::instance()->menuTable;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['parent', 'order'], 'integer'],
            [['data'], 'string'],
            [['name'], 'string', 'max' => 128],
            [['route'], 'string', 'max' => 255],
            [['route'], 'in',
                'range' => Route::getAssignedRoutes(),
                'message' => '找不到名称为"{value}"的路由'
            ],
            [['parent'], 'exist', 'skipOnError' => true, 'targetClass' => Menu::className(), 'targetAttribute' => ['parent' => 'id']],
        ];
    }

    public static function getAvailableMenuWithLevel()
    {
        $query = static::find()->select(['id', 'parent', 'name'])->orderBy(['order'=>SORT_ASC])->asArray()->all();
        $menus = Category::unlimitedForLevel($query, 'parent');

        $result = [];
        foreach ($menus as $menu) {
            $result[$menu['id']] = $menu['prefix'].$menu['name'];
        }
        return $result;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'parent' => '上级菜单',
            'parent_name' => '上级菜单',
            'route' => '路由',
            'order' => '排序',
            'data' => '数据',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParentMenu()
    {
        return $this->hasOne(Menu::className(), ['id' => 'parent']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenus()
    {
        return $this->hasMany(Menu::className(), ['parent' => 'id']);
    }
}
